{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d874e23f-9631-48e0-b635-84e7280bf07b",
   "metadata": {},
   "source": [
    "# SDXL Training / Inference Tutorial\n",
    "\n",
    "### Note:\n",
    "Currently, this notebook must be run in a NeMo container (> 24.09) and open_clip_torch<=2.24.0. An example command to launch the container:\n",
    "\n",
    "```\n",
    "docker run --gpus all -it --rm -v <your_nemo_dir>:/opt/NeMo -v <your_dataset_dir>:/datasets --shm-size=8g \\\n",
    "     -p 8888:8888 --ulimit memlock=-1 --ulimit \\\n",
    "      stack=67108864 <your_nemo_container>\n",
    "```\n",
    "\n",
    "\n",
    "## Introduction\n",
    "\n",
    "This notebook illustrates how to train and perform inference using Stable Diffusion XL with the NeMo Toolkit. Despite differences in model configs, the training and inference procedure is similar as Stable Diffusion.\n",
    "\n",
    "The implementation of Stable Diffusion XL is based on [SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis](https://arxiv.org/abs/2307.01952).\n",
    "\n",
    "This tutorial will guide you through the following topics:\n",
    "\n",
    "1. Training a Stable Diffusion XL model.\n",
    "2. Performing inference with the trained model.\n",
    "\n",
    "## Datasets\n",
    "\n",
    "Please refer to [Dataset Tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Multimodal%20Data%20Preparation.ipynb) for how to prepare a training dataset for Stable diffusion XL.\n",
    "\n",
    "For a pre-cached Stable Diffusion dataset, each webdataset tar file should, at a minimum, include the pickle files that store the pre-cached image and text features:\n",
    "\n",
    "```\n",
    "t0_r0_0.tar\n",
    "|---- 0000.pickle\n",
    "|---- 0001.pickle\n",
    "...\n",
    "```\n",
    "\n",
    "For non-precached Stable Diffusion dataset, each webdataset tar file should contain the raw texts and corresponding images:\n",
    "\n",
    "```\n",
    "t0_r0_0.tar\n",
    "|---- 0000.jpg\n",
    "|---- 0000.txt\n",
    "|---- 0001.jpg\n",
    "|---- 0001.txt\n",
    "...\n",
    "```\n",
    "\n",
    "## Encoders Preparation\n",
    "\n",
    "Depending on whether you precache the dataset, you might also need to first download the image and/or text encoders.\n",
    "\n",
    "### Option 1: Training on Non-Precached Dataset (Use Encoders During Training)\n",
    "\n",
    "#### A. Prepare VAE\n",
    "To download the default VAE for Stable Diffusion:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "730cd137-0fce-4bab-8ac7-219e5c55faf2",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "! wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/vae/diffusion_pytorch_model.safetensors\n",
    "! mkdir -p /sdxl_ckpts\n",
    "! mv diffusion_pytorch_model.safetensors /sdxl_ckpts/vae.safetensors"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "fef8b245-7cee-4048-a9ec-3ada90432a89",
   "metadata": {},
   "source": [
    "The above command will download the default VAE weights from HuggingFace and save it to `/sdxl_ckpts/vae.safetensors`.\n",
    "\n",
    "**Note**: if you want to customize the saved location, make sure it is also reflected in your training config.\n",
    "#### B. Prepare Text Encoder\n",
    "For the text encoders used in Stable Diffusion XL, it will be automatically downloaded by the training script we provide.\n",
    "\n",
    "The type of text encoder used in the sdxl model conditioner can be found in `conditioner_config` in the predefined training configs:\n",
    "\n",
    "```\n",
    "  conditioner_config:\n",
    "    _target_: nemo.collections.multimodal.modules.stable_diffusion.encoders.modules.GeneralConditioner\n",
    "    emb_models:\n",
    "      - is_trainable: false\n",
    "        input_key: captions\n",
    "        ucg_rate: 0.1\n",
    "        emb_model:\n",
    "          _target_: nemo.collections.multimodal.modules.stable_diffusion.encoders.modules.FrozenCLIPEmbedder\n",
    "          layer: hidden\n",
    "          layer_idx: 11\n",
    "      - is_trainable: false\n",
    "        ucg_rate: 0.1\n",
    "        input_key: captions\n",
    "        emb_model:\n",
    "          _target_: nemo.collections.multimodal.modules.stable_diffusion.encoders.modules.FrozenOpenCLIPEmbedder2\n",
    "          arch: ViT-bigG-14\n",
    "          version: laion2b_s39b_b160k\n",
    "          freeze: true\n",
    "          layer: penultimate\n",
    "          always_return_pooled: true\n",
    "          legacy: false\n",
    "```"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8854eb7a-e822-43f6-a1d5-12357049485a",
   "metadata": {},
   "source": [
    "\n",
    "### Option 2: Training on Precached Dataset (Training UNet Only)\n",
    "\n",
    "When using precached dataset (please refer to the [Dataset Tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Multimodal%20Data%20Preparation.ipynb) for details), every text feature and image feature are stored as key-value pairs in `.pickle` file:\n",
    "\n",
    "```\n",
    "{\n",
    " image_key: torch.Tensor(),\n",
    " text_key: torch.Tensor(),\n",
    "}\n",
    "```\n",
    "\n",
    "Make sure in the training config, `cond_stage_key` is associated with `text_key` and `first_stage_key` is associated with `image_key`.\n",
    "\n",
    "We offer an expample script to convert a dataset from `parquet` file to webdataset `tar` files at [parquet_conversion](https://github.com/NVIDIA/NeMo/blob/main/scripts/multimodal_dataset_conversion/parquet_conversion.py). Three different modes of prechaed training are provided, they are:\n",
    "\n",
    "1. No Caching: VAE and Text encoders are loaded during training\n",
    "2. Text only: Only text features are loaded from dataset during training\n",
    "3. Both: Both image and text features are loaded from dataset during training\n",
    "\n",
    "In each mode, the cached components should be saved in its raw format in tarfiles while cached components should be saved as torch.Tensor()."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5762427b-f60c-4dfd-8318-e55771b25354",
   "metadata": {},
   "source": [
    "## Model Config Setup\n",
    "\n",
    "Now we will begin setting up the config file needed for Stable Diffusion training. We will use [sd_train.yaml](https://github.com/NVIDIA/NeMo/blob/main/examples/multimodal/text_to_image/stable_diffusion/conf/sd_xl_base_train.yaml) as the template.\n",
    "\n",
    "1. Modify `model.data.train.dataset_path` so that it has all the webdataset info files you want to train on\n",
    "2. Modify `model.data.webdataset.local_root_path` to point to your dataset path\n",
    "3. Make sure VAE path `model.first_stage_config.from_pretrained` is adjusted if using non-precached dataset\n",
    "4. Make sure the `model.precache mode` is set properly with the dataset you prepared, as detailed above.\n",
    "5. Configure `exp_manager.exp_dir` for experiment save directory\n",
    "6. Configure `exp_manager.wandb_logger_kwargs` and/or `exp_manager.create_tensorboard_logger` if needed"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "70f858b3-f7d5-4678-b380-80582337bc23",
   "metadata": {},
   "source": [
    "**Note**: Please refer to NeMo Toolkit Developer Guide's Stable Diffusion page for more details on in-depth customizations, including all available optimizations.\n",
    "\n",
    "## Training\n",
    "\n",
    "Once everything is set up, training stable diffusion is as simple as running:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "589e3a14-c881-4a56-b2bd-370653059dfc",
   "metadata": {},
   "outputs": [],
   "source": "! torchrun /opt/NeMo/examples/multimodal/text_to_image/stable_diffusion/sd_xl_train.py trainer.max_steps=100 model.data.train.dataset_path=/path/to/wdinfo.pkl model.data.webdataset.local_root_path=/path/to/dataset trainer.devices=1 trainer.num_nodes=1 model.micro_batch_size=1 model.global_batch_size=1 model.first_stage_config.from_pretrained=/sdxl_ckpts/vae.safetensors model.fsdp=False"
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "892d72dd-c4d7-4ca4-a948-168e187af65c",
   "metadata": {},
   "source": [
    "Intermediate checkpoints (during training) and final checkpoint will be saved to `exp_manager.exp_dir` folder. Note that here we use synthetic data for demo purpose."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "087c8b9a-92c3-43d3-86a3-bf7e848dfbd2",
   "metadata": {},
   "source": [
    "## Inference\n",
    "\n",
    "Stable Diffusion XL inference needs a trained NeMo Stable Diffusion checkpoint, along with both the image encoder (VAE) and text encoder (CLIP). The checkpoint can be either a fully trained `.nemo` checkpoint or an intermediate checkpoint from training (typically in `.ckpt` format). \n",
    "\n",
    "### Inference Config Setup\n",
    "\n",
    "Now we will begin setting up the config file needed for Stable Diffusion inference. We will use [sd_xl_infer_v2.yaml](https://github.com/NVIDIA/NeMo/blob/main/examples/multimodal/text_to_image/stable_diffusion/conf/sd_xl_infer_v2.yaml) as the template.\n",
    "\n",
    "We generally use [Classifier Free Guidance](https://arxiv.org/abs/2207.12598) for better visual quality, which can be set at `sampling.base.scale`.\n",
    "\n",
    "NeMo Stable Diffusion supports multiple samplers. Please refer to the developer guide for more details. Samplers can be set at `sampling.base.sampler`.\n",
    "\n",
    "Inference supports a batch of text prompts, which can be set at `infer.prompt`. One can also generate a configurable number of images per prompt by setting `infer.num_samples`. Generated images will be saved to `out_path`.\n",
    "\n",
    "You will also need to set the model checkpoint path at `model.restore_from_path` if you are loading from `.nemo` checkpoint, otherwise, mannually set `unet` checkpoints and `vae` checkpoint at `model.unet_config.from_pretrained` and `model.first_stage_config.from_pretrained`, respectively.\n",
    "\n",
    "### Running the Inference\n",
    "\n",
    "Once everything is set up, Stable Diffusion inference is as simple as running:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e676c5d-d711-489e-8ab7-3ee20046d88d",
   "metadata": {},
   "outputs": [],
   "source": "! torchrun  /opt/NeMo/examples/multimodal/text_to_image/stable_diffusion/sd_xl_infer.py model.restore_from_path=/path/to/stable-diffusion-xl-train.nemo out_path=/sdxl_infer_out"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
